package com.example.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.example.common.interface_constants.Constants;
import com.example.domain.User;
import com.example.domain.dto.UserDto;
import com.example.domain.vo.Result;
import com.example.domain.vo.UserVo;
import com.example.service.WebService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

@RestController
@Slf4j
@RequestMapping("/front")
public class WebController {
    @Autowired
    private WebService webService;

    /**
     * 登录
     *
     * @param userDto
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody UserDto userDto, HttpSession session) {
        UserVo userVo = webService.login(userDto, session);
        return Result.success(userVo);
    }

    /**
     * 注册
     *
     * @param userDto
     * @return
     */
    @PostMapping("/register")
    public Result register(@RequestBody UserDto userDto, HttpSession session) {
        webService.register(userDto, session);
        return Result.success();
    }

    /**
     * 获取验证码
     *
     * @param session
     * @param response
     */
    @GetMapping("/captcha")
    public void getCaptcha(HttpSession session, HttpServletResponse response) {
        // 定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(Constants.CAPTCHA_WIDTH, Constants.CAPTCHA_HEIGHT);
        // 设置返回数据类型
        response.setContentType("image/jpeg");
        // 禁止使用缓存
        response.setHeader("Pragma", "No-cache");
        try {
            // 输出到页面
            lineCaptcha.write(response.getOutputStream());
            // 将 生成的验证码 和 验证码生成时间 存储到session中
            session.setAttribute(Constants.CAPTCHA_KEY, lineCaptcha.getCode());
            session.setAttribute(Constants.CAPTCHA_DATE, new Date());
            // 关闭流
            response.getOutputStream().close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @GetMapping("/PersonInfo/{userId}")
    public Result getPersonInfo(@PathVariable Integer userId) {
        User user = webService.getPersonInfo(userId);
        return Result.success(user);
    }

    @PostMapping("/PersonInfo")
    public Result updatePersonInfo(@RequestBody User user) {
        User u = webService.updatePersonInfo(user);
        return Result.success(u);
    }

    @PostMapping("/validate/password")
    public Result validatePwd(@RequestBody User user) {
        webService.validatePwd(user);
        return Result.success();
    }
}
